// utils/imageUtils.js

/**
 * 将图片URL转换为Base64格式
 * @param {string} imgUrl - 图片地址
 * @returns {Promise} 返回Promise，解析后得到base64字符串
 */
 export function getBase64Sync(imgUrl) {
    return new Promise(function (resolve, reject) {
        let image = new Image();
        image.crossOrigin = 'anonymous';
        image.src = imgUrl;
        image.onload = function () {
            let canvas = document.createElement("canvas");
            canvas.width = image.width;
            canvas.height = image.height;
            let context = canvas.getContext("2d");
            context.drawImage(image, 0, 0, image.width, image.height);
            let ext = image.src.substring(image.src.lastIndexOf(".") + 1).toLowerCase();
            let quality = 0.8;
            let dataurl = canvas.toDataURL("image/" + ext, quality);
            resolve(dataurl);
        };
        image.onerror = reject;
    });
}

/**
 * 将base64格式的数据转换为ArrayBuffer
 * docxtemplater图片模块需要ArrayBuffer格式
 * @param {string} dataURL - base64格式的图片数据
 * @returns {ArrayBuffer|boolean} 返回ArrayBuffer
 */
export function base64DataURLToArrayBuffer(dataURL) {
    const base64Regex = /^data:image\/(png|jpg|jpeg|svg|svg\+xml);base64,/;
    if (!base64Regex.test(dataURL)) {
        return false;
    }
    const stringBase64 = dataURL.replace(base64Regex, "");
    let binaryString;
    if (typeof window !== "undefined") {
        binaryString = window.atob(stringBase64);
    } else {
        binaryString = new Buffer(stringBase64, "base64").toString("binary");
    }
    const len = binaryString.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
        const ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
    }
    return bytes.buffer;
}